/*
 * 类Compilation是对整个编译流程的封装
*/

#include <filesystem>
#include "Compilation.h"
#include "Tokenizer.h"
#include <llvm/Support/WithColor.h>
#include <llvm/Support/Path.h>
#include <lld/Common/Driver.h>
#include <lld/Common/ErrorHandler.h>

const char* Compilation::readFile(const std::string &filepath, llvm::SMLoc include_loc) {
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> file_or_err = llvm::MemoryBuffer::getFile(filepath);

    if (std::error_code err = file_or_err.getError()) {
        llvm::WithColor::error(llvm::errs()) << "Error reading " << filepath << ": " << err.message() << "\n";
        exit(EXIT_FAILURE);
    }

    auto id = srcMgr.AddNewSourceBuffer(std::move(*file_or_err), include_loc);
    return srcMgr.getMemoryBuffer(id)->getBuffer().begin();
}

Token * Compilation::tokenizeFile(const std::string &filepath, Token **end_token, bool skip_header, SMLoc include_loc) {
    const char *buffer = readFile(filepath, include_loc);
    Token *tok = Tokenizer(*this).tokenize(buffer, end_token);
    return tok;
}

void Compilation::run() {
    Token *end = nullptr;
    Token *tok = tokenizeFile(mainFile, &end);

    dumpTokens(tok, "All the tokens:");
}